package until

import (
	"context"
	"errors"
	"net/http"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/gin-gonic/gin"
	"github.com/zhangcook/jwt_go"
	"github.com/zhangcook/jwt_go/config"
)

// JwtMiddlewareGin 实现gin框架的中间件解析
func JwtMiddlewareGin(secretKey string) app.HandlerFunc {

	if len(secretKey) == 0 {
		panic("jwt密钥不能为空")
	}

	return func(ctx context.Context, c *app.RequestContext) {
		// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localSstorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
		token := c.Request.Header.Get("token")
		if token == "" {
			token = c.Query("token")
			if token == "" {
				c.JSON(http.StatusUnauthorized, gin.H{
					"code": http.StatusUnauthorized,
					"msg":  "未登录",
					"data": nil,
				})
				c.Abort()
				return
			}

		}
		j := jwt_go.NewAuthenticationInformation(secretKey)
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			if errors.Is(err, config.TokenExpired) {
				if errors.Is(err, config.TokenExpired) {
					c.JSON(http.StatusUnauthorized, gin.H{
						"code": http.StatusUnauthorized,
						"msg":  "授权以过期",
						"data": nil,
					})
					c.Abort()
					return
				}
			}

			c.JSON(http.StatusUnauthorized, gin.H{
				"code": http.StatusUnauthorized,
				"msg":  "未登录",
				"data": nil,
			})
			c.Abort()
			return
		}
		c.Set("permissionInformation", claims.PermissionInformation)
		c.Set("userId", claims.UserId)
		c.Next(ctx)
	}
}
